<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\v2\model;

use think\cache\driver\Redis;
use think\Db;

use think\Model;
use think\Cache;
use app\common\model\SystemConfig;
use app\common\model\YunFengModel;
class UserInfo extends Model 
{	

    protected $name = 'user_info';
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $autoWriteTimestamp = 'datetime';
    protected $options = [
        // 缓存类型为File
        'type'  =>  'File', 
        // 缓存有效期为七天
        'expire'=>  604800, 
        //缓存前缀
        'prefix'=>  'think',
         // 指定缓存目录
        'path'  =>  APP_PATH.'runtime/cache/',
    ];
    /**
     * 通过uid修改用户资料
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-09-11T15:13:28+0800
     * @param    [type]                   $param [description]
     * @param    [type]                   $uid   [description]
     * @return   [type]                          [description]
     */
    public function updateDataByUId($param, $uid)
    {
        $applyModel = new Apply;
        $hasApply = $applyModel->hasApply($uid);
        if($hasApply){
            $this->error = "您还有订单未处理完成，暂不能修改资料";
            return false; 
        }
        foreach ($param as $key => $value) {
            if(empty($value)){
                $this->error = "所有项必填且不能为0";
                return false; 
            }
        }
        unset($param['os']);
        unset($param['mobile_type']);

        //若有姓名则不更新姓名 2018年5月31日15:08:26
        $oldName = $this->where('uid',$uid)->value('name');
        if($param['name'] && !empty($oldName) && $oldName != $param['name']){
            $this->error = "姓名不可更改";
            return false; 
        }

        //新增认证时间
        $param += $this->authDate($param);

        $res = $this->allowField(true)->save($param, ['uid' => $uid]);
        if(false!==$res){
            return true;
        }
        $this->error = '资料保存失败';
        return false;
    }

    /**
     * 认证时间
     * @author cxr <1481746137@qq.com>
     * @param $param
     * @return array
     */
    public function authDate($param){
        $date = date('Y-m-d H:i:s', time());
        $data = [];
        if(!empty($param['address']))
            $data['baseinfo_auth_date'] = $date;
        if(!empty($param['id_card_img1']))
            $data['idcard_auth_date'] = $date;
        return $data;
    }

    /**
     * 通过uid 获取 name 没有name 就用phone代替
     * @zwr
     * @DateTime 2017-06-30T10:00:28+0800
     * @return   string                  
     */
    public function getNameByuid($uid)
    {
    	return $res = $this->where('uid',$uid)->value('name');
    }

    public function getPhone($uid)
    {
    	return  $this->where('uid',$uid)->value('phone');
    }	
    /**   
     * [getIdLastSix 获取身份证后六位数]
     * @param  [type] $uid [description]
     * @return [type]      [description]
     */
    public function getIdLastSix($uid,$num)
    {
        if(!$uid)
        {
            $this->error = '参数错误';
            return false;
        }
        $datetime = date('Y-m-d',time());
        $count = Db::name('id_log')->where(['uid'=>$uid,'addtime'=>['egt',$datetime]])->count('id');
        //输错三次今天无法验证
        if($count >= 3)
        {
            $this->error = '验证三次失败，请明天再试';
            return false;
        }
        //连接文件缓存
        Cache::connect($this->options);
        //取缓存
        if(Cache::has('_user_'.$uid))
        {
            $idCard = Cache::get('_user_'.$uid);
        }else{
            $idCard = $this->getIdCard($uid);
            if(!$idCard)
            {
                $this->error = '未完善信息，无法验证';
                return false;
            }
            Cache::set('_user_'.$uid,$idCard,604800);
        }
        if(substr($idCard,-6,6) !== $num)
        {
            Db::name('id_log')->insert(['uid'=>$uid,'addtime'=>date('Y-m-d H:i:s',time())]);
            $this->error = '验证失败,今日还剩余'.(2-$count).'次机会';
            return false;
        }
        return true;
    }
    public function getIdCard($uid)
    {
        return $this->where('uid',$uid)->value('id_card');
    }
    /**
     * 个人资料
     * @author   yhq
     * @DateTime 2017-07-27 15:45
     * @return   array
     */
    public function getMyInfo($uid, $param=''){
    	$data = $this->where(['uid'=>$uid])
    	->field('name,uid,id_card_img1,id_card_img2,id_card_img3,zhima,id_card,mon_income,company,phone,address,bank_card_number,open_gid,wechat_id,payday,zmf,negative_img,job,directories,age')
    	->find();
    	if(!$data)
        {
            $phone = Db::name('user')->where('uid',$uid)->value('phone'); 
            $map['uid']       = $uid;
            $map['phone']     = $phone;
            $map['rand_code'] = md5($map['uid'].microtime());
            $add = $this->allowField(true)->save($map);
            if(!$add)
            {
                $this->error = '未查询到数据';
                return false;   
            }
            return $this->getMyInfo($uid);
    	}
        
    	$data = $data->toArray();

        # 查询卡片信息
        if(empty($data['open_gid'])){
            $gear = Db::name('gear')->where('status',1)->order('money')->select();
            if(!$gear) {  
                $this->error = '系统错误';
                return false;
            }
            $gid = $gear[0]['id'];
            $open_gid = array($gid); //默认解锁金额最小的卡片
        }else{
            $open_gid = json_decode($data['open_gid'],true);  //解锁的卡片
        }

        # 根据解锁卡片的查询可申请最大金额
        $arr_money = array();
        foreach ($open_gid as $value) {
            $arr_money[] = Db::name('gear')->where('id', $value)->value('money');
        }
        sort($arr_money);
        $max_money = end($arr_money);  //可申请最大总金额
        $data['max_money'] = $max_money;

        unset($data['open_gid']);
        $res = $data;
        unset($res['phone']);
        unset($res['max_money']);
        
        if(!empty($res['bank_card_number'])){
            $str = $res['bank_card_number'];
            $data['bank_card_number'] = substr($str,0,4).' **** **** '.substr($str,-4);
        }
    
        $count = count($res); //总字段
        $viod  = 0; //未填写字段
        foreach ($res as $key => $value) 
        {
            if(is_null($value) || $value=='')
            {
                $viod = $viod + 1;
                $data[$key] = '';
            }
        }

        // 云峰 
        // $count = $count+1;
        // if(YunFengModel::isYunFengAuth($uid)==false){
        //     $viod = $viod + 1;
        // }

        // QQ同步助手
        if($data['directories'] != 1){
            $viod = $viod + 1;
        }

        $data['integrity'] = (int)ceil(100*($count-$viod)/$count); //资料完整度

        $applyModel          = new Apply;
        $gearModel           = new Gear;
        $apply               = $applyModel->where(['uid'=>$data['uid']])->order('id desc')->find(); //上次借款单
        $apply_status        = $gearModel->apply_status($apply);
        $data['applyStatus'] = $apply_status['status'];
        $data['applyInfo']   = $apply_status['info'];
        $data['part']        = $apply_status['part'];
        unset($data['uid']);
        unset($data['directories']);
        unset($data['operator_state']);

    	return $data;
    }	


    /**
     * 获取支付信息
     * @Author      火星车11号
     * @email       704184317@qq.com
     * @create_time 2017-10-11T19:15:42+0800
     * @param      
     * @return     
     */
    public function getCardbyUid($uid)
    {
        return $this->where(["uid"=>$uid])->field('name,bank_card_number')->find();
    }

    /**
     * 运营商认证
     * @param  [type] $param [description]
     * @return [type]        [description]
     */
    public function operatorAuth($uid,$param)
    {
        $UserInfo = $this->where('uid', $uid)->field('name,id_card,phone,bind_mob')->find();
        if(empty($UserInfo['name'])||empty($UserInfo['id_card'])||empty($UserInfo['phone'])){
            $this->error='请先完成银行卡绑定';
            return false;
        }

        # 验证接收字段
        $validate = validate('operator');
        if (!$validate->check($param)) {
            $this->error = $validate->getError();
            return false;
        }

        $param['name']      = $UserInfo['name'];
        $param['idNumber']  = $UserInfo['id_card'];
        $param['phone']     = $UserInfo['phone'];
        $param['channel']   = config('operator_channel');
        $param['returnUrl'] = config('domainpath')['api'].'/V2/returnUrl';
        $param['notifyUrl'] = config('domainpath')['api'].'/V2/notifyUrl';
        $param['userId']    = time().$uid;

        $res = curlPost('http://api.qhweidai.com/api/calldetails', $param);
        if(!$res){
            $this->error='数据获取失败，请重试';
            return false; 
        }
        $arr = json_decode($res,true);
        if($arr['code']!='200'){
            $this->error='数据获取失败，请重试';
            return false; 
        }
        $url = $arr['data']['tianji_api_tianjireport_collectuser_response']['redirectUrl'];

        $len = 0;
        foreach ($param as $key => $value) {
            if(strstr($key, 'emergencyPhone')){
              $len += 1;  
          }
        }
        for ($i=1; $i <= $len ; $i++) { 
            $four_contacts[$i-1]['phone']    = $param["emergencyPhone{$i}"];
            $four_contacts[$i-1]['relation'] = $param["emergencyRelation{$i}"];
            $four_contacts[$i-1]['name']     = $param["emergencyName{$i}"];
            $four_contacts[$i-1]['no']       = $i;
        }
        $add['uid'] = $uid;
        $add['four_contacts'] = json_encode($four_contacts);
        $add['savedate'] = date('Y-m-d H:i:s');
        $count = Db::name('secret_about')->where('uid',$uid)->count();
        if($count>0){
            $res = Db::name('secret_about')->where('uid',$uid)->update($add);
        }else{
            $res = Db::name('secret_about')->insert($add);
        }

        if(false!==$res){
           return $url;  
        }
        $this->error = '请求失败';
        return false;
    }


    /**
     * 是否验证运营商
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-09T23:21:54+0800
     * @param    [type]   $uid 用户id
     * @return   [type]   
     */
    public function checkOperator($uid)
    {
        $operator = $this->where('uid', $uid)->value('operator_state');
        $data['operator'] = $operator=='login'? 1:0;
        return $data;
    }


    /**
     * 运营商状态
     * @param  array|string   $userInfo  用户信息或者用户id
     * @return array           $result   状态码和描述 0:未认证  1:已认证  2:认证中  3:认证失败  4:认证过期
     */
    public function operatorStatus($userInfo)
    {
        if(!is_array($userInfo) && !is_object($userInfo) && !$userInfo['operator_state'] && !$userInfo['mongo_operator_report']){
            $uid = $userInfo;
            $userInfo = $this->where('uid',$uid)->find(); 
        }

        $status = '0';
        $info   = '运营商未认证'; 

        if(in_array($userInfo['operator_state'], ["login","report","crawl"])){
            $status = '2';
            $info   = '运营商认证中';
            if(!empty($userInfo['mongo_operator_report'])){ // 检验是否存在报告
                $para['mongoRes']  = $userInfo['mongo_operator_report'];
                $para['idNumber']  = $userInfo['id_card'];
                $para['channel']   = config('operator_channel');
                $para['userId']    = $userInfo['operator_id'];
                $para['search_id'] = $userInfo['operator_search_id'];

                $res = curlPost('api.qhweidai.com/api/Detailreport', $para);
                if(json_decode($res, true)['code'] == 200){  // 有报告
                    $status = '1';
                    $info   = '运营商已认证';
                    $max = empty(config('OPERATOR_OVERDUE_TIME')) ? 0 : config('OPERATOR_OVERDUE_TIME');
                    $day = (time() - strtotime($userInfo['operator_update_time']))/(24*3600);
                    if($day > $max){  // 已过期
                        $status = '4';
                        $info = '运营商认证已过期';
                    }
                }else { //无报告
                    $status = '3';
                    $info   = '运营商认证失败，请重新认证';
                    # 清空数据是为了防止出现：认证失败后重新认证直接显示认证失败，而不是认证中状态
                    $this->save(['mongo_operator_report' => null], ['uid' => $userInfo['uid']]);
                }
            }else if(time() - strtotime($userInfo['operator_update_time']) > 300){ // 五分钟还没回调自动设置失败
                $status = '3';
                $info   = '运营商认证超时，请重新认证';
            }
        }
        
        $result = [
            "status" => $status,
            "info"   => $info
        ];

        return $result;
    }


    /**
     * 验证状态
     * @return [type] [description]
     */
    public function authState($uid){
        $UserInfo = $this->where('uid',$uid)->find();
        if(!$UserInfo){
            $this->error='获取失败';
            return false;
        }
        $result = [
            'identity'    =>'0',  //身份认证
            'base'        =>'0',  //基本信息
            'operator'    =>'0',  //运营商
            'bank'        =>'0',  //银行卡
            'other'       =>'0',  //云峰
            'directories' =>$UserInfo['directories'],  //是否qq同步
        ];
        if(!empty($UserInfo['id_card_img1'])&&!empty($UserInfo['id_card_img2']) &&!empty($UserInfo['id_card_img3']) ){
            $result['identity'] = '1';
        }
        if(!empty($UserInfo['company']) && !empty($UserInfo['address']) && !empty($UserInfo['zhima']) && !empty($UserInfo['name']) && !empty($UserInfo['mon_income']) && !empty($UserInfo['wechat_id']) && !empty($UserInfo['payday']) && !empty($UserInfo['zmf']) && !empty($UserInfo['negative_img']) && !empty($UserInfo['job']) && !empty($UserInfo['age'])){           
            $result['base'] = '1';
        }

        // 运营商
        $operatorStatus = $this->operatorStatus($UserInfo);
        $result['operator'] = $operatorStatus['status'];

        // 银行卡
        $bankno = Db::name('user_bank_card')->where(['bank_card_number'=> $UserInfo['bank_card_number'],'status' => 1])->value('user_nm');
        if(!empty($UserInfo['bank_card_number']) && !empty($bankno)){
            $result['bank'] = '1';
        }   
        // 银行卡是否认证（三要素模式）     
        if(config('PAY_MODE')==1 && !empty($UserInfo['bank_card_number']) ){
            $result['bank'] = '1';
        }

        // 云峰
        // $isYunFengAuth = YunFengModel::isYunFengAuth($uid);
        // if($isYunFengAuth){
        //     $result['other'] = $isYunFengAuth;
        // }

        return $result;
    }


    /**
     * 验证状态
     * @return [type] [description]
     */
    public function authStateByInfo($UserInfo){

        $result = [
            'identity'    =>'0',  //身份认证
            'base'        =>'0',  //基本信息
            'operator'    =>'0',  //运营商
            'bank'        =>'0',  //银行卡
            'other'       =>'0',  //云峰
            'directories' =>$UserInfo['directories'],  //是否qq同步
        ];
        if(!empty($UserInfo['id_card_img1'])&&!empty($UserInfo['id_card_img2'])&&!empty($UserInfo['id_card_img2']) ){
            $result['identity'] = '1';
        }
        if(!empty($UserInfo['company']) && !empty($UserInfo['address']) && !empty($UserInfo['zhima']) && !empty($UserInfo['qq']) && !empty($UserInfo['mon_income']) && !empty($UserInfo['wechat_id']) && !empty($UserInfo['payday']) && !empty($UserInfo['zmf']) && !empty($UserInfo['negative_img']) && !empty($UserInfo['job'])){
            $result['base'] = '1';
        }

        // 运营商
        #暂时这样
        if(!empty($UserInfo['mongo_operator_report'])){
            $result['operator'] = '1';
        }
//        $operatorStatus = $this->operatorStatus($UserInfo);
//        $result['operator'] = $operatorStatus['status'];


        // 银行卡
        if(!empty($UserInfo['bank_card_number'])){
            $result['bank'] = '1';
        }

        // 云峰
        // $isYunFengAuth = YunFengModel::isYunFengAuth($uid);
        // if($isYunFengAuth){
        //     $result['other'] = $isYunFengAuth;
        // }

        return $result;
    }


    /**
     * 通话详单同步回调
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-04T16:02:49+0800
     * @param    array  $param  接受参数
     * @return   boolean
     */
    public function returnUrl($param)
    {       
        $map['operator_outUniqueId'] = $param['outUniqueId'];
        $map['operator_state']       = $param['state'];
        $map['operator_update_time']   = date('Y-m-d H:i:s');
        $userId = substr($param['userId'], 10); //去掉前十位（获取详单时拼接的时间戳）
        $update = $this->allowField(true)->save($map, ['uid' => $userId]);
        if(false!==$update){
            return true;
        }
        $this->error = '更新失败';
        return false;
    }

    /**
     * 通话详单异步回调
     * @author   yhq <934797303@qq.com>
     * @DateTime 2017-08-04T16:04:21+0800
     * @param    array  $param  接受参数
     * @return   boolean
     */
    public function notifyUrl($param) {
        $map['operator_search_id']     = $param['search_id'];
        $map['mongo_operator_report']  = $param['mongoRes'];
        $map['operator_id']            = $param['userId'];
        $map['operator_state2']        = $param['notifystate'];
        $map['operator_account']       = $param['account'];
        $map['operator_update_time']   = date('Y-m-d H:i:s');
        $where['operator_outUniqueId'] = $param['outUniqueId'];

        $update = $this->allowField(true)->save($map, $where);
        if(false!==$update){
            return true;
        }
        $this->error = '更新失败';
        return false;
    }
    /**
     * [getData 获取一条信息]
     * @param  string $field [description]
     * @param  array  $where [description]
     * @return [type]        [description]
     */
/*    public function getData($field = '*', $where = []){
        return $this->field($field)->where($where)->find();
    }*/

    /**
     * 根据手机号查询用户信息
     * @author Warner <934797303@qq.com>
     * @date   2018-04-28
     * @param  [type]     $phone [手机号]
     * @return [type]
     */
    public function getUserInfoByPhone($phone)
    {
        $uid = $this->where('phone',$phone)->order('id desc')->value('uid');
        if(!$uid){
            $this->error = '用户不存在';
            return false;
        }

        return $this->getMyInfo($uid);
    }

    /**
     * 根据手机号更新用户信息
     * @author Warner <934797303@qq.com>
     * @date   2018-04-28
     * @return [type]
     */
    public function updateUserInfoByPhone($param)
    {
        $uid = $this->where('phone',$param['phone'])->order('id desc')->value('uid');
        if(!$uid){
            $this->error = '用户不存在';
            return false;
        }

        return $this->updateDataByUId($param, $uid);
    }

    public function getMyOverdueDays($uid,$orderNumber)
    {
        $data = model('admin/Documentary')->field('appoint_time')->where(array('order_number'=>$orderNumber,'uid'=>$uid))->find()->toArray();
        $appoint_time = $data['appoint_time'];
        $times = time() - strtotime($appoint_time);
        if($times < 0){
            return array('msg'=>'当前订单未逾期');
        }
        $days = $times/(24*3600);
        $days = ceil($days);
        return array('days'=>$days);
    }


    public function getLinkman($uid='')
    {
        $data = Db::name('secret_about')->field('four_contacts')
                                            ->where('uid','=',$uid)
                                            ->find();
        if(!$data){
            return false;
        }

        $data = json_decode($data['four_contacts'],true);
        return $data;
    }

    /**
     * 五小时内认证redis自减-1
     * @param string $uid
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function countRedis($uid='')
    {
        if(empty($uid)){
            return false;
        }
        $userInfo = $this->where('uid',$uid)
            ->whereNotNull('business_id')
            ->field('business_id,create_time')->find();
        if(!$userInfo){
            return false;
        }
        if((strtotime($userInfo['create_time'])+3600*5)>time()){

            $redis = new Redis(array('host'=>'127.0.0.1'));
            //白天8-19
            $h = date('H');
            $minute = date('i');
            $h = $h+$minute/60;

            $bidDay ='_n';
            if($h >=0 && $h< 18.75)
            {
                $bidDay ='_d';
            }
            $daytime = date('Ymd');

            $arrbus = explode('-', $userInfo['business_id']);
            $arrbus = array_unique($arrbus);
            foreach ($arrbus as $key => $bid)
            {
                $check = $redis->get('wdyjishu:'.config('_BANK_PINGTAIFF').'_register:'.$daytime.$bidDay.':'.$bid);
                if ($check>0) {
                    $res = $redis->dec('wdyjishu:'.config('_BANK_PINGTAIFF').'_register:'.$daytime.$bidDay.':'.$bid);
                }else{
                    return false;
                }
            }
        }
    }
}
